<template>
  <el-dialog
    v-model="visible"
    :title="`${title}数据`"
    :destroy-on-close="true"
    :close-on-click-modal="false"
  >
    <el-tabs v-if="title==='修改'" v-model="activeName" @tab-click="saveLoading=false">
      <el-tab-pane label="基础数据" name="basicData"></el-tab-pane>
      <el-tab-pane label="国家分区" name="nationalDivision"></el-tab-pane>
      <el-tab-pane label="重量模板" name="weightTemp"></el-tab-pane>
    </el-tabs>
    <div v-else class="title">基础数据</div>
    <component :is="componentsMap[activeName]" ref="componentRef" :basic-info="basicInfo" />
    <template #footer>
      <div>
        <el-button
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          保存
        </el-button>
        <el-button @click="cancel">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {
  ref,
  defineExpose,
  defineEmits,
} from 'vue'
import basicData from './BasicData.vue'
import nationalDivision from './nationalDivision.vue'
import weightTemp from './WeightTemp.vue'
import { getcostPriceList } from '@/api/BusinessConfig/costPriceManagement'

interface componentsExpose {
   save:(type?:string) => Promise<any>
}
type componentsList = 'basicData' | 'nationalDivision' | 'weightTemp'
const componentsMap = {
  basicData,
  nationalDivision,
  weightTemp,
}
const emit = defineEmits(['changeList'])
const visible = ref<boolean>(false)
const saveLoading = ref<boolean>(false)
const title = ref('修改')
const basicInfo = ref({})
const componentRef = ref<componentsExpose>()
const activeName = ref<componentsList>('basicData')
const cancel = () => {
  visible.value = false
}
const save = () => {
  saveLoading.value = true
  switch (activeName.value) {
    case 'basicData':
      componentRef.value.save(title.value)
      .then((res) => {
        if (res) {
          emit('changeList')
          if (title.value === '新增') {
            cancel()
          }
        }
      }).finally(() => {
        saveLoading.value = false
      })
      break
    case 'nationalDivision':
      componentRef.value.save().finally(() => {
        saveLoading.value = false
      })
      break
    case 'weightTemp':
      componentRef.value.save().finally(() => {
        saveLoading.value = false
      })
      break
    default:
      ((e:never):never => { throw new Error(`Unexpected object: ${ e }`) })(activeName.value)
  }
}
const open = (t = '修改', row) => {
  activeName.value = 'basicData'
  title.value = t
  visible.value = true
  const data = { pageNum: 0, pageSize: 0, id: row.id }
  getcostPriceList(data).then(res => {
    basicInfo.value = res.data[0]
  })
}
defineExpose({
  open,
})
</script>
<style lang="less">
.top-right-btn {
  margin: 20px 600px;
}
</style>
